package com.erebus.centroller;


import com.erebus.model.dto.Draft;
import com.erebus.model.dto.TokenUser;
import com.erebus.model.dto.User;
import com.erebus.model.dto.UserDto;
import com.erebus.service.EightCharactersService;
import com.erebus.utils.JwtUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
public class EightCharactersController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EightCharactersService eightCharactersService;


    // 初始化用户
    @GetMapping("/initUser")
    public String initUser(HttpServletRequest request) throws ParseException {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            tokenUser = JwtUtils.parseToken(token);
        } else {
            return "请先登录";
        }
        User user = new User();
        user.setName(tokenUser.getUsername());
        Draft draft = new Draft();
        user.setDraft(draft);
        Boolean hasKey = redisTemplate.hasKey(user.getName());
        if (hasKey != null && hasKey) {
            System.out.println("Key 存在");
            redisTemplate.delete(tokenUser.getUsername());
        }
        redisTemplate.opsForValue().set(user.getName(), user, 1, TimeUnit.DAYS);
        return "初始化成功";
    }

    // 八字排盘
    @GetMapping("/paipan")
    public String paipan(HttpServletRequest request) throws ParseException, JsonProcessingException {
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            tokenUser = JwtUtils.parseToken(token);
        }


        User user = (User) redisTemplate.opsForValue().get(tokenUser.getUsername());

        UserDto userDto = eightCharactersService.paipan(user.getName());

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(userDto);
        System.out.println(json);
        return json;
    }

    // 保存时间
    @GetMapping("/saveTime/{time}")
    public String getEightCharacters(@PathVariable(value = "time") String time, HttpServletRequest request) throws ParseException {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            tokenUser = JwtUtils.parseToken(token);
        }


        User user = (User) redisTemplate.opsForValue().get(tokenUser.getUsername());
        // 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        // 解析字符串为 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.parse(time, formatter);
        int year = dateTime.getYear();         // 年
        int month = dateTime.getMonthValue();  // 月 (1 ~ 12)
        int day = dateTime.getDayOfMonth();    // 日
        int hour = dateTime.getHour();         // 时
        int minute = dateTime.getMinute();     // 分
        user.setYear(year);
        user.setMonth(month);
        user.setDay(day);
        user.setHour(hour);
        user.setMinute(minute);
        redisTemplate.delete(tokenUser.getUsername());
        redisTemplate.opsForValue().set(tokenUser.getUsername(), user);

        return "success";

    }

    // 保存性别
    @GetMapping("/saveSex/{sex}")
    public String saveSex(@PathVariable(value = "sex") String sex, HttpServletRequest request) throws ParseException {
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            tokenUser = JwtUtils.parseToken(token);
        }

        User user = (User) redisTemplate.opsForValue().get(tokenUser.getUsername());
        user.setSex(sex);
        redisTemplate.delete(tokenUser.getUsername());
        redisTemplate.opsForValue().set(tokenUser.getUsername(), user);

        return "success";
    }


}
